package com.hospital.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.domain.pojo.User;
import com.hospital.domain.utils.JwtUtils;
import com.hospital.domain.utils.Result;
import com.hospital.domain.utils.UserContext;
import com.hospital.mapper.UserMapper;
import com.hospital.service.DoctorService;
import com.hospital.service.PatientService;
import com.hospital.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;


@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    // private final DoctorService doctorService;
    // private final PatientService patientService;
    private DoctorService doctorService;

    @Autowired
    public void setDoctorService(@Lazy DoctorService doctorService) {
        this.doctorService = doctorService;
    }
    private PatientService patientService;

    @Autowired
    public void setPatientService(@Lazy PatientService patientService) {
        this.patientService = patientService;
    }
    @Override
    public Result<User> login(String account, String pw) {
        if(account.isBlank() || pw.isBlank()){
            return Result.fail("账号或密码错误");
        }
        User user = lambdaQuery().eq(User::getUName, account).one();
        if(user == null){
            System.err.println("用户不存在");
            return Result.fail("账号或密码错误");
        }
        if(user.getUState() == 0){
            return Result.fail("账号已被冻结");
        }
        if(!user.getUPw().equals(pw)){
            return Result.fail("账号或密码错误");
        }
        String token = JwtUtils.generateToken(user);
        log.info("登陆成功");
        return Result.ok(token, user);
    }

    @Override
    public Result<String> signup(String account, String pw, Integer role, Integer state, Integer id) {
        if(lambdaQuery().eq(User::getUName, account).exists()){
            return Result.fail("账号已存在");
        }
        save(new User(account, pw, role, state, id));
        return Result.ok("注册成功");
    }

    @Override
    public Result<String> removeUser(Integer userId) {
        User user = lambdaQuery().eq(User::getUId, userId).one();
        if(user == null){
            return Result.fail("该用户不存在");
        }
        removeById(userId);
        if(user.getURole() == 0){
            //病人账号
            patientService.removeById(user.getId());
        }
        else if(user.getURole() == 1){
            //医生账号
            doctorService.removeById(user.getId());
        }
        else{
            return Result.fail("暂无权限删除管理员账号");
        }
        return Result.ok("删除成功");
    }


}
